<template>
  <div>
    <h1>扫码界面</h1>
    <!-- 扫码：<input id="text" type="text" v-model="text" placeholder="光标定位后扫码获取文本" autofocus style="width:80%" /> -->
    <van-cell-group>
      <van-field left-icon="scan" right-icon="warning-o" v-model="text" label="扫码:" placeholder="光标定位后扫码获取文本"
                 autofocus clearable :disabled="isForbidden" center>
        <template #button>
          <van-button size="normal" type="primary" @click="parseTable()" color="#6b8bb0">解析</van-button>
        </template>
      </van-field>
    </van-cell-group>

<!--    <van-button type="primary" icon="qr" @click="showPopup()" color="#6b8bb0" style=" margin-top:1%;margin-right: 1%;">生成二维码-->
<!--    </van-button>-->
<!--    <van-button icon="plus" type="primary" @click="storeBtnClick()">暂存</van-button>-->

    <!-- <div class="bom">
      工号：<input type="text" :value="bomData.LACODSEQ" readonly>
      零件图号：<input type="text" :value="bomData.TY" readonly>
      零件名称：<input type="text" :value="bomData.REQUIRES" readonly>
      工序号/工序名称：<input type="text" :value="bomData.JYBZ" readonly>
      单件号：<input type="text" :value="bomData.SYMBOL" readonly>
    </div> -->

    <!-- <van-row gutter="10">
      <van-col span="5">
        <van-cell title="工号：" :value="bomData.LACODSEQ" />
      </van-col>
      <van-col span="5">
        <van-cell title="零件图号：" :value="bomData.TY" />
      </van-col>
      <van-col span="5">
        <van-cell title="零件名称：" :value="bomData.REQUIRES" />
      </van-col>
      <van-col span="4">
        <van-cell title="工序号/工序名称：" :value="bomData.JYBZ" />
      </van-col>
      <van-col span="5">
        <van-cell title="单件号：" :value="bomData.SYMBOL" />
      </van-col>
    </van-row> -->

    <van-row>
      <van-col>
        <van-cell title="工号：" :value="bomData.LACODSEQ" />
      </van-col>
      <van-col>
        <van-cell title="零件图号：" :value="bomData.TY" />
      </van-col>
      <van-col>
        <van-cell title="零件名称：" :value="bomData.REQUIRES" />
      </van-col>
      <van-col>
        <van-cell title="工序号/工序名称：" :value="bomData.JYBZ" />
      </van-col>
      <van-col>
        <van-cell title="单件号：" :value="bomData.SYMBOL" />
      </van-col>
    </van-row>

    <!-- <div>
      <vue-scroll :ops="ops" style="width:100%;height:100%">
        <div class="data-box">
          <van-row class="th-row" style="display:flex;">
            <van-col style="width:80px">编号</van-col>
            <van-col style="width:80px">工序/工步</van-col>
            <van-col style="width:80px">检验性质</van-col>
            <van-col style="width:80px">检验内容</van-col>
            <van-col style="width:80px">符号</van-col>
            <van-col style="width:80px">专检字段</van-col>
            <van-col style="width:80px">最大值</van-col>
            <van-col style="width:80px">最小值</van-col>
            <van-col style="width:80px">测量值</van-col>
            <van-col style="width:80px">检验结果备注</van-col>
            <van-col style="width:80px">是否合格</van-col>
          </van-row>

          <van-row class="td-row" :style="{background:index %2==0?'#fff':'#ffcccc'}"
            v-for="(item,index) in dataList" :key="item.ID">
            <van-col style="width:80px">{{index + 1}}</van-col>
            <van-col style="width:80px">{{ item.LACODSEQ }}</van-col>
            <van-col style="width:80px">{{ item.TY == 1 ? "定量":"定性" }}</van-col>
            <van-col style="width:80px">{{item.REQUIRES}}</van-col>
            <van-col style="width:80px">{{item.SYMBOL}}</van-col>
            <van-col style="width:80px">{{item.JYBZ}}</van-col>
            <van-col style="width:80px">{{item.MAXVAL}}</van-col>
            <van-col style="width:80px">{{item.MINVAL}}</van-col>
            <van-col style="width:80px">
              <van-field v-model="item.VAL" type="number" placeholder="输入数字"
                style="border: 1px solid #ccc;background-color: #f5fafe;"></van-field>
            </van-col>
            <van-col style="width:80px">
              <van-cell-group border>
                <van-field v-model="item.RESULT" type="text"
                  style="border: 1px solid #ccc;background-color: #f5fafe;"></van-field>
              </van-cell-group>
            </van-col>
            <van-col style="width:80px">
              <van-radio-group v-model="item.AAA">
                <van-radio name="合格" style=" margin-bottom:15px;">合格</van-radio>
                <van-radio name="不合格">不合格</van-radio>
              </van-radio-group>
            </van-col>
          </van-row>
        </div>
      </vue-scroll>
    </div> -->

    <div>
      <table width="100%" class="table" id="tablevalue">
        <tr style="background-color: #d4e8f9;font-size: 14px;">
          <th>行号</th>
          <th>工序/工步</th>
          <th>检验性质</th>
          <th style="width: 180px;">检验内容</th>
          <th>符号</th>
          <th>专检字段</th>
          <th>最大值</th>
          <th>最小值</th>
          <!-- 用户填写 -->
          <th>测量值</th>
          <th>检验结果备注</th>
          <th>是否合格</th>
        </tr>
        <tr v-for="(item,index) in dataList" :key="item.ID">
          <td>{{index + 1}}</td>
          <td>{{ item.LACODSEQ }}</td>
          <td>{{ item.TY === 1 ? "定量":"定性" }}</td>
          <td>{{item.REQUIRES}}</td>
          <td>{{item.SYMBOL}}</td>
          <td>{{item.JYBZ}}</td>
          <td>{{item.MAXVAL}}</td>
          <td>{{item.MINVAL}}</td>
          <!-- <td>
            <div>
              <van-field v-model="item.VAL" type="number" placeholder="输入数字"
                style="border: 1px solid #ccc;background-color: #f5fafe;"></van-field>
            </div>

          </td>
          <td>
            <div>
              <van-field v-model="item.RESULT" type="text"
                style="border: 1px solid #ccc;background-color: #f5fafe;"></van-field>
            </div>
          </td> -->
          <td><input type="text" v-model="item.VAL" placeholder="输入数字"
                     style="border: 1px solid #ccc;background-color: #f5fafe;width: 100px;" /></td>
          <td><input type="text" v-model="item.RESULT"
                     style="border: 1px solid #ccc;background-color: #f5fafe;width: 40px;" /></td>

          <td>
            <!-- 单选框 -->
            <!-- <input type="radio" value="合格" v-model="item.AAA">合格
            <input type="radio" value="不合格" v-model="item.AAA">不合格 -->
            <van-radio-group v-model="item.AAA" style="background-color: #f5fafe;width: 80px;">
              <van-radio name="合格" style=" margin-bottom:15px;">合格</van-radio>
              <van-radio name="不合格">不合格</van-radio>
            </van-radio-group>
          </td>

        </tr>
      </table>
    </div>

    <van-button type="primary" icon="qr" @click="showPopup()" color="#6b8bb0" style=" margin-top:1%;margin-right: 1%;">生成二维码
    </van-button>
<!--    <van-button icon="plus" type="primary" @click="storeBtnClick()">暂存</van-button>-->
    <!-- <button @click="downloadE()">下载</button> -->
    <van-popup v-model="show">
      <div id="qrcode" ref="qrcode"></div>
    </van-popup>


<!--展示底部数据-->
    <van-list
        v-model="loading"
        :finished="finished"
        :finished-text=msg
        @load="onLoad"
    >
      <van-cell v-for="item in list" :key="item" :title="item" :border="false" />
    </van-list>


  </div>
</template>

<script>
import QRCode from 'qrcodejs2'
import {
  Toast
} from 'vant';

var qrcode;
export default {
  name: 'Table',
  // props:['timeId'],  // 将路由中传递的参数timeId解耦到组件的props属性上
  data() {
    return {
      list: [],
      loading: false,
      finished: false,
      msg:"",

      isForbidden: false, //读取暂存区数据后禁止扫码输入
      show: false, //控制展示二维码弹窗
      text: "", //解析的文本
      qrText: "", //最终生成二维码的文本
      storeHead: {},
      storeBody: [],
      bomData: { //数组第一个元素  代表本次传输特征
        "ID": "",
        "LACODSEQ": "", //工号
        "TY": "", //零件图号
        "REQUIRES": "", //零件名称
        "SYMBOL": "", //单件号
        "JYBZ": "", //工序号/工序名称
        "MAXVAL": "",
        "MINVAL": "",
        "VAL": "",
        "RESULT": "",
        "AAA": ""
      },
      dataList: [{
        "ID": "",
        "LACODSEQ": "", //工序/工步
        "TY": "", //检验性质：1定量，0定性
        "REQUIRES": "", //检验内容
        "SYMBOL": "", //符号
        "JYBZ": "", //专检字段
        "MAXVAL": "", //最大值
        "MINVAL": "", //最小值
        // 下面字段需要用户填写
        "VAL": "", //测量值
        "RESULT": "", //检验结果备注
        "AAA": "" //是否合格
      }],
    }
  },
  watch: {
    show: function() {
      //当show为true时展示二维码
      if (this.show) {
        this.generateQRcode();
      }
    },
    // dataList: function (){
    //   this.msg = `本页面一共有${this.dataList.length}条数据`
    // }
  },
  mounted() {
    const timeId = this.$route.params.timeId;
    const index = this.$route.params.index;

    //读取暂存区数据后禁止扫码输入
    if (timeId != undefined) {
      this.isForbidden = true;
      // console.log(`timeId:${timeId}`);
      // console.log(`index:${index}`);
      console.log(`isForbidden:${this.isForbidden}`);
      this.dataList = JSON.parse(localStorage.getItem(timeId));
      const bomList = JSON.parse(localStorage.getItem("bomList"));
      this.bomData = bomList[index];
    }
  },
  methods: {
    onLoad() {
      // 异步更新数据
      // setTimeout 仅做示例，真实场景中一般为 ajax 请求
      // setTimeout(() => {
      //   for (let i = 0; i < 10; i++) {
      //     this.list.push(this.list.length + 1);
      //   }
      //
      //   // 加载状态结束
      //   this.loading = false;
      //
      //   // 数据全部加载完成
      //   if (this.list.length >= this.dataList.length) {
      //     this.finished = true;
      //   }
      // }, 1000);
      // this.list.push(`本页面一共有${this.dataList.length}条数据`);
      this.list.push("数据到底了！");
        for (let i = 0; i < 2; i++) {
          this.list.push("");
        }
        // 加载状态结束
        this.loading = false;
        // this.finished = true;
        // 数据全部加载完成  this.dataList.length
        if (this.list.length >= 2) {
          this.finished = true;
        }
    },

    showPopup() {
      this.show = true;
    },
    parseTable() {
      if (this.text == "" || this.text == null) {
        // 弹窗提示扫码
        Toast('请先扫码！');
        return;
      }
      try {
        var newDataList = JSON.parse(this.text);
      } catch (e) {
        //TODO handle the exception
        //不符合JSON格式会解析失败
        Toast.fail('解析失败！');
        this.text = "";
        return;
      }

      // Vue.set(app, "dataList", newDataList);
      this.bomData = newDataList[0];
      this.bomData.JYBZ = newDataList[1].LACODSEQ.split(":")[1];
      //获取newDataList[0]之外的其他数据
      this.dataList = newDataList.slice(1);

      //qrcode清除
      // qrcode.clear();
      this.$refs.qrcode.innerHTML = '';
    },
    generateQRcode() {
      // 生成二维码前先判断有没有数据
      if (this.bomData.ID === "" || this.bomData.LACODSEQ === "") {
        Toast.fail('数据为空，请先扫码解析！');
        return;
      }
      // 获取整个表格数据
      let tableData = this.dataList.map(item => {
        return {
          ID: item.ID,
          SYMBOL: item.SYMBOL,
          VAL: isNaN(parseFloat(item.VAL)) ? "" : parseFloat(item.VAL),
          RESULT: item.RESULT == null ? "" : item.RESULT,
          AAA: item.AAA == null ? "" : item.AAA
        };
      });


      let newBomData = {
        ID: this.bomData.LACODSEQ,
        SYMBOL: this.bomData.TY,
        VAL: this.bomData.REQUIRES,
        RESULT: this.bomData.JYBZ,
        AAA: this.bomData.SYMBOL
      };

      // 把零件信息bomData放到tableData[0]的位置返回
      tableData.unshift(newBomData);

      // 进行下面的操作，比如发送到后端或保存到本地
      this.qrText = JSON.stringify(tableData);
      // alert(this.qrText);
      // this.$nextTick 是 Vue.js 提供的一个方法，用于在 DOM 更新后执行回调函数
      this.$nextTick(function() {
        this.showQrcode();
      })
    },
    showQrcode() {
      // document.getElementById("qrcode").innerHTML = "";
      //this.$refs.refName用于获取对应组件，它与Vue的响应式系统结合得更好，并且可以避免直接操作DOM带来的问题。
      this.$refs.qrcode.innerHTML = "";

      qrcode = new QRCode('qrcode', { // 第一个入参是组件id
        text: this.qrText, // 生成二维码的文本
        width: 400,
        height: 400,
        colorDark: '#000000', // 二维码色
        colorLight: '#ffffff', // 背景色
        correctLevel: QRCode.CorrectLevel.L // 容错等级L、M、Q、H，H是heigh，最高，所以二维码看起来很密
      });

    },

    // 点击下载app二维码
    // downloadE是一个按钮事件，点击按钮下载
    downloadE(name) {
      var canvasData = this.$refs.qrcode.getElementsByTagName('canvas')
      var a = document.createElement("a");
      var event = new MouseEvent("click"); // 创建一个单击事件
      a.href = canvasData[0].toDataURL("image/png");;
      a.download = "drcQrcode";
      a.dispatchEvent(event); // 触发a的单击事件
    },


    storeBtnClick() {
      const ID = this.bomData.ID;
      // 暂存前先判断有没有数据
      if (this.bomData.ID === "" || this.bomData.LACODSEQ === "") {
        Toast.fail('数据为空，请先扫码解析！');
        return;
      }

      // 生成一个基于当前时间的字符串timeId,作为存储传输唯一标识
      const timeId = this.generateTimeID();
      // console.log(`Generated timeId: ${timeId}`);
      this.bomData.timeId = timeId;

      var bomList = JSON.parse(localStorage.getItem('bomList'));
      if (bomList === null) {
        bomList = [];
      }

      bomList.unshift(this.bomData);
      localStorage.setItem('bomList', JSON.stringify(bomList));
      localStorage.setItem(timeId, JSON.stringify(this.dataList));

      try {
        this.$router.push({
          path: '/list'
        });
        // 如果跳转成功，可以在这里添加成功的逻辑
        Toast.success('暂存成功！');
      } catch (error) {
        console.error('Navigation failed:', error);
        // 处理跳转失败的情况
        Toast.fail('暂存失败！');
      }
    },
    generateTimeID() {
      //输出格式 YYYY-MM-DD HH:MM:SS
      const currentDate = new Date();
      const formattedDate = currentDate.toISOString().split('T')[0] + ' ' + currentDate.toTimeString().split(
          ' ')[0];
      return formattedDate;
    }
  }
}
</script>

<style>
.table {
  border: 1px solid #cad9ea;
  color: #666;
}

.table th {
  background-repeat: repeat-x;
  height: 30px;
}

.table td,
.table th {
  border: 1px solid #cad9ea;
  padding: 0 1em 0;
}

.table tr.alter {
  background-color: #f5fafe;
}

#qrcode {
  display: flex;
  justify-content: center;
  align-items: center;
  /* 可选：设置 div 的宽高等样式 */
  /* width: 300px;
  height: 300px;
  background-color: lightgray; */
}
</style>
